package com.example.hotel.config;

import com.example.hotel.filter.NewCorsFilter;
import com.example.hotel.filter.CustomAuthenticationFilter;
import com.example.hotel.filter.TokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsUtils;

/**
 * WebSecurityConfig
 *
 * @author
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) //开启方法权限注解支持
public class WebSecurityConfig
        extends WebSecurityConfigurerAdapter {

    @Qualifier("userDetailServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private TokenFilter tokenFilter;

    @Autowired
    private NewCorsFilter newCorsFilter;

    /**
     * 密码模块：
     * 在User模块中使用
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .csrf().disable();

        // 基于Token 不需要SESSION
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // login register 不需要验证
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/api/user/login").permitAll();
        http.authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/api/login",
                        "/api/user/login",
                        "/api/user/register/individual",
                        "/api/loc/**", "/api/user/getImg/{userId}",
                        "/api/user/uploadImg/{userId}", "/api/hotel/uploadImg/{hotelId}")
                .permitAll();

        http.authorizeRequests().anyRequest().authenticated();

        // 登录配置
        http.formLogin()
//                .successHandler(authenticationSuccessHandler)
//                .failureHandler(authenticationFailureHandler)
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

        // 登出配置
        http.logout().logoutUrl("/api/user/logout").logoutSuccessHandler(logoutSuccessHandler);

        http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterAfter(tokenFilter, UsernamePasswordAuthenticationFilter.class);
//        http.addFilter(newCorsFilter);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 注入UserDetailsService
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(authenticationFailureHandler);
        filter.setFilterProcessesUrl("/api/user/login");
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

}

